const userModel=require('../modules/user.js')
const statusCode=require('../util/status-code.js')
class UserController {
  /**
 * 创建用户
 * @param ctx
 * @returns {Promise<void>}
 */
 static async create(ctx){
   const user=ctx.request.body;
   if(user.username&&user.password){
    const existUser=await userModel.findUserByName(user.username);
    if(existUser){
      ctx.response.status=403;
      ctx.body=statusCode.ERROR_403('用户已经存在',[])
    }else {
      await userModel.create(user);
      const newUser=await userModel.findUserByName(user.username);

      ctx.response.status=200;
      ctx.body=statusCode.SUCCESS_200('创建用户成功',[],'')
    }
   }else {
     ctx.response.status=412;
     ctx.body=statusCode.ERROR_412('创建失败，参数错误',[])
   }
 }

   /**
  * 查询用户
  * @param ctx
  * @returns {Promise<void>}
  */
  static async getUserInfo(ctx){
    let request =ctx.request;
    let req_query = request.query;
    let username=req_query.username;
    try{
      let userData=await userModel.findUserByName(username);
      ctx.response.status = 200;
      ctx.body = statusCode.SUCCESS_200('查询成功', userData,'')
    }catch(e){
      ctx.response.status = 412;
      ctx.body = statusCode.ERROR_412('查询失败，authorization error!')
    }
  }

  /**
  *查询用户你列表
  *@param ctx
  *@returns {Promise.<void>}
  *@method get
  */
  static async getUserList(ctx){
    let userList;
    try {
      userList=await userModel.findAllList();
      ctx.response.status=200;
      ctx.body=statusCode.SUCCESS_200('获取用户列表成功',userList,'')
    } catch (e) {
      ctx.response.status=412;
      ctx.body=statusCode.ERROR_412('获取用户列表失败',[])
    }
  }

  /**
  *删除用户
  *@param ctx
  *@returns {Promise<void>}
  *@method post
  */
  static async deleteUser(ctx){
    const getData=ctx.request.body;
    let id=getData.id;
    if(id&&!isNaN(id)){
      try {
        let result=await userModel.delete(id);
        if(result){
          ctx.response.status=200;
          ctx.body=statusCode.SUCCESS_200('删除成功',[],'');
        }else {
          ctx.response.status=412;
          ctx.body=statusCode.ERROR_412('删除失败',[])
        }
      } catch (e) {
        ctx.response.status=412;
        ctx.body=statusCode.ERROR_412('删除失败',[])
      }
    }else {
      ctx.response.status=412;
      ctx.body=statusCode.ERROR_412('ID字段必须传',[])
    }

  }
}
module.exports=UserController;
